package org.ghost.parallel.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest {
    private final Logger logger = LoggerFactory.getLogger(ReentrantLockTest.class);
    private static ReentrantLock reentrantLock = new ReentrantLock(true);
    private int sum = 0;

    public void addLock(int val) {
        try {
            reentrantLock.lock();
            sum += val;
            logger.info("*****sum={}", sum);
        } finally {
            reentrantLock.unlock();
        }
    }

    public void addTryLock(int val) {
        try {
            if (reentrantLock.tryLock(1, TimeUnit.SECONDS)) {
                sum += val;
                logger.info("*****sum={}", sum);
            } else {
                logger.info("*****获取锁失败,sum={}", sum);
            }
        } catch (InterruptedException e) {
            logger.error("*****addTryLock出现异常,sum={},{}", sum, e);
        } finally {
            if (reentrantLock.isHeldByCurrentThread()) {
                reentrantLock.unlock();
            }
        }
    }

    public void add(int val) {
        sum += val;
        logger.info("*****sum={}", sum);
    }

    public void printSum() {
        logger.info("*****final result:{}", sum);
    }
}
